#!/usr/bin/env python3.10
# -*- encoding: utf-8 -*-
"""
@File    :   article_test.py
@Time    :   2024/01/19 09:35:45
@Author  :   windstarry 
@Version :   1.0
"""
# here put the import lib

from typing import List, Optional,Union
from datetime import datetime
from ninja import Schema, Router, Field, Query, FilterSchema, UploadedFile, Form, File
from article.models import Article
from django.shortcuts import get_object_or_404

from utils.auth import data_permission, get_user_info_from_token
from utils.response import Response,R


class BaseFilters(FilterSchema):
    creator_id: int = Field(None, alias="creator_id")


class Filters(BaseFilters):
    title: str = Field(None, alias="title")
    content: str = Field(None, alias="content")
    cate: str = Field(None, alias="cate_id")
    id: str = Field(None, alias="id")


class CategorySchema(Schema):
    id: int
    cate_name: str
    cate_alias: str


class ArticleInSchema(Schema):
    title: str = Field(None, alias="title")
    content: str = Field(None, alias="content")
    cate_id: int = Field(...,description="分类id")
    # 文章封面为str或者binary
    cover_img:Union[str,UploadedFile]= Field(None, description="文章封面")
    status: str = Field(..., description="发布状态")
    


class ArticleSchema(Schema):
    Id: int = Field(None, alias="id")
    title: str = Field(None, alias="title")
    content: str = Field(None, alias="content")
    cate_id: int = Field(None, alias="cate.id")
    cate_name: Optional[str] = None
    author: Optional[str] = None
    pub_date: datetime = Field(None, alias="update_datetime")

    @staticmethod
    def resolve_cate_name(obj):
        if not obj.cate:
            return
        return f"{obj.cate.cate_name}"

    @staticmethod
    def resolve_author(obj):
        if not obj.creator:
            return
        return f"{obj.creator.username}"


router = Router()


@router.get("/articles", response=List[ArticleSchema])
def articles_list(request, filters: Filters = Query(...)):
    filters = data_permission(request, filters)
    articles = Article.objects.select_related("cate")
    articles = filters.filter(articles)
    return articles


@router.post("/article/add", response=R)
def article_create(request, article: ArticleInSchema=Form(...)):
    data = article.dict()
    data.pop("cover_img")
    data['status'] = 1 if data.get("status")=="已审核" else 0
    user_info = get_user_info_from_token(request)
    if user_info is None:
        raise ValueError("token校验失败")
    # 创建时默认添加创建人、修改者
    data["creator_id"] = user_info["id"]
    data["modifier"] = user_info["username"]
    obj = Article.objects.create(**data)
    cover_img = request.FILES.get("cover_img")
    cover_img_format = cover_img.name.split('.')[-1]
    if cover_img:
        # 上传图片
        obj.cover_img.save(f'article_{obj.id}.{cover_img_format}', cover_img)
    return R.ok(msg="添加成功")


@router.get("/article/{id}", response=ArticleSchema)
def article_detail(request, id: int):
    request_user = get_user_info_from_token(request)
    article = Article.objects.filter(id=id, creator_id=request_user["id"]).first()
    return article


@router.put("/article/{id}", response=ArticleSchema)
def article_update(request, id: int, article: ArticleInSchema):
    data = article.dict()
    user_info = get_user_info_from_token(request)
    if user_info is None:
        raise ValueError("token校验失败")
    # 更新时默认添加修改人
    data["modifier"] = user_info["username"]
    instance = get_object_or_404(Article, id=id, creator_id=user_info["id"])
    for attr, value in data.items():
        setattr(instance, attr, value)
    instance.save()
    return instance


@router.delete("/article/{id}")
def article_delete(request, id: int):
    user_info = get_user_info_from_token(request)
    if user_info is None:
        raise ValueError("token校验失败")
    instance = get_object_or_404(Article, id=id, creator_id=user_info["id"])
    instance.delete()
    return Response(msg="删除成功")
